package com.kingbi.system.people.jsfBean;

import java.sql.SQLException;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.kingbi.common.MD5;
import com.kingbi.system.people.model.PeopleModel;
import com.kingbi.system.people.service.PeopleService;
import com.kingbi.system.userRole.model.UserRoleModel;
import com.kingbi.util.ConstantFiles.UserConstant;

public class PeopleJsfBean extends PeopleDataBean {

	// 页面导航
	private String outcome;
  
	// 错误信息提示
	FacesMessage message;
	private PeopleService peopleService;
	
	private String roleCheckbox = "";

    private String roleChecked = "";

    private String oldpassword = "";

	static Logger logger = Logger.getLogger(PeopleJsfBean.class);


	public void setPeopleService(PeopleService peopleService) {
		HttpServletRequest request = (HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest();
		String searchTag = (String) request.getParameter("searchTag");
		String userId = request.getParameter("userId");
		String userName = request.getParameter("userName");

		this.peopleService = peopleService;

		if (searchTag != null && searchTag.equals("isSearch")) {
			search();
		}
		if (userId != null) {
			if (!userId.equals("")) {
				super.setUserId(userId);
			}
		}
		if (userName != null) {
			if (!userName.equals("")) {
				super.setUserName(userName);
			}
		}
	}

	/**
	 * 页面导航
	 * 
	 * @return
	 */
	public String outcome() {
		logger.warn("outcomeoutcome");
		return outcome;
	}

	/**
	 * 导向添加页面
	 * 
	 * @return
	 */
	public String preAdd() {
		
		getEmptyJsfBean();
		logger.warn("**********************perAdd()");

		return "addPeople";
	}

	/**
	 * 导向修改页面
	 * 
	 * @return
	 */
	public String preUpdate() {

		logger.warn("**********************perUpdate()");
		try {
			int n = tData.getRowCount();
			for (int i = 0; i < n; i++) {
				tData.setRowIndex(i);
				if (selected.isSelected()) {
					
					setChecked(false);
					PeopleDataBean tempModel = new PeopleDataBean();
					tempModel = (PeopleDataBean) tData.getRowData();
					PeopleDataBean updateModel = new PeopleDataBean();
					updateModel = peopleService.findUserInfo(tempModel.getUserId());
					getJsfDataBean(updateModel);
					super.setIsEdit("UPD");
					
				}
				
			}

		} catch (Exception e) {
			e.printStackTrace();
			return "failure";
		}
		logger.warn("***************执行完毕*****************");
		return "updatePeople";
	}

	/**
	 * 提交添加操作
	 * 
	 * @return
	 */
	public String add() {    
		logger.warn("**********************save()" + peopleService);
		PeopleModel peopleModel = new PeopleModel();
		peopleModel = super.getJsfModel();
		try {
			peopleService.savePeople(peopleModel);
			getEmptyJsfBean();
			search();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	/**
	 * 提交添加或修改操作
	 * 
	 * @return
	 */  
	public String saveOrupdate() {
		System.out.println("save or update");
		logger.warn("**********************saveOrupdate()");
		PeopleModel peopleModel = new PeopleModel();
		    
		peopleModel = super.getJsfModel();
		if (super.getIsEdit() == null || "".equals(super.getIsEdit())) {
			peopleModel.setPassword(new MD5().getMD5ofStr(peopleModel.getPassword()));
			peopleModel.setValid("1");
		}
		String roles = this.roleChecked;
		String[] role = null;
		if (roles.length() > 1) {
			roles = roles.substring(0, roles.length() - 1);
			role = roles.replaceAll(",", "~").split("~");
		}
		try {
			int maxId = peopleService.getMaxId();
			peopleService.saveUser(peopleModel, role);
			for (int i = 0; i<role.length;i++) {
				String r = role[i];
				UserRoleModel userRoleModel = new UserRoleModel();
				
				userRoleModel.setUserRoleID(maxId+i+1);
				userRoleModel.setUserId(peopleModel.getUserId());
				userRoleModel.setRoleCode(r);
				peopleService.savePeopleRole(userRoleModel);
			}
			
			//getEmptyJsfBean();
			search();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	public String delete() {
		System.out.println("qqqqqqqqqqqqqqqqqqqqqqqqqq");
		try {
			int n = tData.getRowCount();
			for (int i = 0; i < n; i++) {
				tData.setRowIndex(i);
				if (selected.isSelected()) {
					setChecked(false);
					PeopleDataBean tempModel = new PeopleDataBean();
					tempModel = (PeopleDataBean) tData.getRowData();
					PeopleModel deleteModel = getModelData(tempModel);
					deleteModel.setValid("0");
					peopleService.savePeople(deleteModel);
					selected.setSelected(false);
				}
			}
			getEmptyJsfBean();
			search();
		} catch (Exception e) {
		    e.printStackTrace();
			return "failure";
		}
		return "success";
	}
   
	/**
     * 从其它页面返回到查询列表页面
     * @return
     */
    public String backToSearch()
    {
        getEmptyJsfBean();
        search();
        return "success";
    }
	/**    
	 * 查询方法
	 * 
	 * @return
	 */
	public String search() {
		System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
		tData = null;
		selected = null;
		logger.warn("**********************search()");
		String s_new_CurrentPage = (String) FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap().get("newCurrentPage");
		String s_query_flag = (String) FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap().get("queryFlag");

		if (s_query_flag != null && s_query_flag.equals("ispage")) {
			listUpdateFlag = false;
		} else {
			listUpdateFlag = true;
		}
    
		StringBuffer queryCond = new StringBuffer();
		
		if (this.getQueryName().length() > 0) {
			queryCond.append(" having pu.user_name like '%"
					+ this.getQueryName().replaceAll("'", " ").replace("\""," ") + "%'");
		}
		if (this.getQueryMobile().length() > 0) {
			queryCond.append(" having pu.mobile like '%"
					+ this.getQueryMobile().replaceAll("'", " ").replace("\""," ") + "%'");
		}
		if(this.getQueryName().length() == 0 && this.getQueryMobile().length() == 0){
            getEmptyJsfBean();
        }
		PeopleModel peopleModel = new PeopleModel();
		peopleModel = super.getJsfModel();
		peopleModel.setValid("1");
    
		/*
		 * 总记录数
		 */
		if (listUpdateFlag) {
			try {
				setRecordCount(peopleService.queryUserCount(queryCond.toString()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		/*
		 * 当前页号
		 */
		if (s_new_CurrentPage != null && !s_new_CurrentPage.equals("")
				&& !s_new_CurrentPage.equals("null")) {
			if (!(s_new_CurrentPage.equals("newPage"))) {
				setCurrentPage(Integer.parseInt(s_new_CurrentPage));
			}
		} else {
			setCurrentPage(1);
		}
		/*
		 * 处理分页
		 */
		dealPage(getRecordCount(), getPageRecord(), getCurrentPage());
		/*
		 * 根据分页获取数据记录
		 */

		try {
			setStartRecordNum(((getCurrentPage() - 1) * getPageRecord() + 1) < 0 ? 0
					: (getCurrentPage() - 1) * getPageRecord() + 1);
			setEndRecordNum(getPageRecord() * getCurrentPage());
			setItems(peopleService.getUserItems(queryCond.toString(),(getCurrentPage() - 1) * getPageRecord() + 1,
					getPageRecord() * getCurrentPage(),getRecordCount()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "success";
	}   

	//获取用户Id
	 public String preUpdSelfPwd() {
		Object userId = ((HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false))
				.getAttribute(UserConstant.USER_MAP_KEY_ID);
		try {
			PeopleModel updateModel = peopleService.LoadUserBySQL(userId
					.toString());
			getJsfDataBean(updateModel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "selfPwd";

	}
	
	// 校验用户原密码
	public void validateUserPwd(FacesContext context, UIComponent component,
			Object obj) throws ValidatorException {
		try {   
			PeopleModel updateModel = this.getJsfModel();
			System.out.println("--"+new MD5().getMD5ofStr(obj.toString())+"--");
			System.out.println("--"+updateModel.getPassword()+"--");
			if (!(new MD5().getMD5ofStr(obj.toString()).equals(updateModel.getPassword()))) {
				throw new ValidatorException(new FacesMessage("oldpassword","原密码不正确！"));
			}
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}
	
  //获得当前登录用户的Id	
	public String preUpdSelfInfo(){
        Object userId = ((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false)).getAttribute(UserConstant.USER_MAP_KEY_ID);
        try {
			PeopleModel updateModel = peopleService.LoadUserBySQL(userId
					.toString());
			getJsfDataBean(updateModel);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return "selfInfo";

    }
	
	// 修改用户密码
	 public String updSelfPwd(){
	        PeopleModel updateModel = this.getJsfModel();
	        updateModel.setPassword(new MD5().getMD5ofStr(updateModel.getPassword()));
	        try
	        {
			peopleService.savePeople(updateModel);
			this.setUserName("");
		} catch (Exception e) {
			e.printStackTrace();
			return "failure";
		}
	        search();
	        return "success";
	    }
   // 修改个人用户信息
	 public String updSelfInfo(){
		 PeopleModel updateModel = this.getJsfModel();
	        try {
			peopleService.savePeople(updateModel);
			this.setUserName("");
		} catch (Exception e) {
			e.printStackTrace();
			return "failure";
		}
		search();
		return "success";
	    }
	 
	 public String getRoleCheckbox() {
			try {
				String checkboxStr = peopleService.getCheckboxStr(this.getUserId());
				this.setRoleCheckbox(checkboxStr);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return roleCheckbox;
		}

	public void setRoleCheckbox(String roleCheckbox) {
		this.roleCheckbox = roleCheckbox;
	}

	public String getRoleChecked() {
		return roleChecked;
	}

	public void setRoleChecked(String roleChecked) {
		this.roleChecked = roleChecked;
	}

	public String getOldpassword() {
		return oldpassword;
	}

	public void setOldpassword(String oldpassword) {
		this.oldpassword = oldpassword;
	}

	
	
	

}
